package com.jubotech.business.web.service;

import com.alibaba.fastjson.JSONObject;
import com.jubotech.business.web.dao.StatDataDao;
import com.jubotech.business.web.domain.StatData;
import com.jubotech.business.web.query.StatDataQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class StatService {

    @Autowired
    private StatDataDao statDataDao;

    @Transactional
    public Integer saveBatch(List<StatData> data) {
        Date now=new Date();
        for (StatData datum : data) {
            datum.setCreate_time(now);
        }
        //每300条批量插入
        Integer count = 0;
        for (int i = 0; i < data.size(); i += 300) {
            count+=statDataDao.saveBatch(data.subList(i, Math.min(data.size(), i + 300)));
        }
        return count;
    }

    public JSONObject queryStatData(StatDataQuery query) {
        List<StatData> statData = statDataDao.queryStatData(query);
        JSONObject jsonObject = new JSONObject();
        for (StatData statDatum : statData) {
            // 名称的组成可能是 a.b 或 a.b.c
            String[] split = statDatum.getName().split("\\."); // 注意要转义点
            JSONObject current = jsonObject;
            for (int i = 0; i < split.length - 1; i++) {
                String key = split[i];
                if (!current.containsKey(key) || !(current.get(key) instanceof JSONObject)) {
                    current.put(key, new JSONObject());
                }
                current = current.getJSONObject(key);
            }
            String lastKey = split[split.length - 1];
            Object value = null;
            switch (statDatum.getValue_type()) {
                case 0:
                    value = statDatum.getValue();
                    break; // 文本
                case 1:
                    value = statDatum.getValue_num();
                    break; // 数字
                case 2:
                    value = statDatum.getValue_decimal();
                    break; // 浮点数
                case 3:
                    value = JSONObject.parse(statDatum.getValue_text());
                    break; // text
                case 4:
                    value = statDatum.getValue_date();
                    break; // 日期
                default:
                    value = statDatum.getValue();
            }
            current.put(lastKey, value);
        }
        return jsonObject;
    }
}
